<template>
  <div>
    <a-card>
      <a-row :style="{ minHeight: '600px' }" :gutter="[32, 8]">
        <a-col :span="12">
          <p class="text-xl font-bold mb-4">维修类型</p>

          <div class="my-3 flex justify-end">
            <a-form layout="inline" :model="kindSearchState">
              <a-form-item>
                <a-input v-model:value="kindSearchState.name"></a-input>
              </a-form-item>

              <a-form-item>
                <a-space>
                  <a-button type="primary" @click="onSearchKind">搜索</a-button>
                  <a-button type="primary" @click="addKind">新增</a-button>
                </a-space>
              </a-form-item>
            </a-form>
          </div>

          <a-table
            :columns="columns"
            size="small"
            :dataSource="kindTails"
            :bordered="true"
          >
            <template #bodyCell="{ record, column, text }">
              <template v-if="column.dataIndex === 'action'">
                <a-button type="primary" @click="editKind(record)"
                  >编辑</a-button
                >
                <a-popconfirm
                  title="确认删除吗?"
                  ok-text="Yes"
                  cancel-text="No"
                  @confirm="delKind(record)"
                >
                  <a-button type="primary" danger>删除</a-button>
                </a-popconfirm>
              </template>
            </template>
          </a-table>

          <a-modal centered v-model:open="open" title="管理" :footer="false">
            <a-form
              ref="formKindRef"
              :model="kindState"
              :label-col="{ span: 2 }"
              :wrapper-col="{ span: 24 }"
              class="border border-gray-200 solid"
            >
              <a-form-item
                label="父级"
                name="pid"
                :rules="[
                  ruleStore.getRule('pid')
                    ? ruleStore.getRule('pid')
                    : { required: false },
                ]"
              >
                <a-select v-model:value="kindState.pid">
                  <a-select-option
                    v-for="(k, ind) in kindList"
                    :key="ind"
                    :value="k.id"
                  >
                    {{ k.union_name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item
                label="名称"
                name="name"
                :rules="[
                  ruleStore.getRule('name')
                    ? ruleStore.getRule('name')
                    : { required: false },
                ]"
              >
                <a-input v-model:value="kindState.name"></a-input>
              </a-form-item>
              <a-form-item>
                <a-button
                  type="primary"
                  style="width: 100px"
                  @click="onSubmitKind"
                  >提交</a-button
                >
              </a-form-item>
            </a-form>
          </a-modal>
          <p class="text-xl font-bold mb-4">树形结构</p>

          <a-tree
            checkable
            :tree-data="kindData"
            :showLine="true"
            defaultExpandAll
            :fieldNames="{ title: 'name', key: 'id', children: 'children' }"
          >
          </a-tree>
        </a-col>
        <a-col :span="12">
          <p class="text-xl font-bold mb-4">工时</p>
          <a-button type="primary" @click="addEventHour">添加工时</a-button>
          <a-button type="primary" @click="previewExcel">excel原始</a-button>
          <a-modal
            centered
            v-model:open="excelOpen"
            title="原始数据"
            width="100%"
            wrap-class-name="full-modal"
            :footer="false"
          >
            <ExcelPreview excelUrl="http://localhost:3000/sheet/origin.xlsx" />
          </a-modal>
          <a-modal
            centered
            v-model:open="manhourOpen"
            title="管理"
            :footer="false"
          >
            <a-form
              ref="formManhourRef"
              :model="manhourForm"
              :label-col="{ span: 3 }"
              :wrapper-col="{ span: 24 }"
            >
              <a-form-item
                label="车型"
                name="kind_id"
                :rules="[
                  ruleStore.getRule('kind_id')
                    ? ruleStore.getRule('kind_id')
                    : { required: false },
                ]"
              >
                <a-select v-model:value="manhourForm.kind_id">
                  <a-select-option
                    v-for="(k, index) in options.kind_data"
                    :value="k.id"
                  >
                    {{ k.union_name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item
                label="服务"
                name="service_id"
                :rules="[
                  ruleStore.getRule('service_id')
                    ? ruleStore.getRule('service_id')
                    : { required: false },
                ]"
              >
                <a-select
                  v-model:value="manhourForm.service_id"
                  show-search
                  placeholder="关键词搜索"
                  :default-active-first-option="false"
                  :show-arrow="false"
                  :filter-option="false"
                  style="width: 100%"
                  :not-found-content="null"
                  :options="options.service_data"
                  @search="handleServiceSearch"
                  @change="handleServiceChange"
                ></a-select>
              </a-form-item>
              <a-form-item
                label="工时"
                name="score"
                :rules="[
                  ruleStore.getRule('score')
                    ? ruleStore.getRule('score')
                    : { required: false },
                ]"
              >
                <a-input-number
                  style="width: 100%"
                  v-model:value="manhourForm.score"
                ></a-input-number>
              </a-form-item>

              <a-form-item :wrapper-col="{ offset: 4, span: 2 }">
                <a-button
                  type="primary"
                  style="width: 100px"
                  @click="onSubmitManhour"
                  >提交</a-button
                >
              </a-form-item>
            </a-form>
          </a-modal>

          <vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvent">
            <template #service="{ row }">
              {{ row.service ? row.service.name : "" }}
            </template>
            <template #kind="{ row }">
              {{ row.kind ? row.kind.union_name : "" }}
            </template>
            <template #action="{ row }">
              <a-button type="primary" @click="editEventHour(row)"
                >编辑</a-button
              >
              <a-popconfirm title="确定删除吗？" @confirm="delEventHour(row)">
                <a-button type="primary" danger>删除</a-button>
              </a-popconfirm>
            </template>
          </vxe-grid>
          <p class="text-xl font-bold mb-4">服务项目</p>
          <a-button type="primary" @click="addService">新增</a-button>
          <vxe-grid
            ref="xServiceGrid"
            v-bind="gridServiceOptions"
            v-on="gridServiceEvent"
          >
            <template #action="{ row }">
              <a-button type="primary" @click="editEventService(row)"
                >编辑</a-button
              >
              <a-popconfirm
                title="确定删除吗？"
                @confirm="delEventService(row)"
              >
                <a-button type="primary" danger>删除</a-button>
              </a-popconfirm>
            </template>
          </vxe-grid>
          <a-modal
            centered
            v-model:open="serviceOpen"
            title="管理"
            :footer="false"
          >
            <a-form
              ref="formServiceRef"
              :model="serviceForm"
              :label-col="{ span: 2 }"
              :wrapper-col="{ span: 24 }"
              class="border border-gray-200 solid"
            >
              <a-form-item
                label="名称"
                name="name"
                :rules="[
                  ruleStore.getRule('name')
                    ? ruleStore.getRule('name')
                    : { required: false },
                ]"
              >
                <a-input v-model:value="serviceForm.name"></a-input>
              </a-form-item>
              <a-form-item
                label="编码"
                name="code"
                :rules="[
                  ruleStore.getRule('code')
                    ? ruleStore.getRule('code')
                    : { required: false },
                ]"
              >
                <a-input v-model:value="serviceForm.code"></a-input>
              </a-form-item>

              <a-form-item>
                <a-button
                  type="primary"
                  style="width: 100px"
                  @click="onSubmitService"
                  >提交</a-button
                >
              </a-form-item>
            </a-form>
          </a-modal>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import useRuleStore from "@/store/modules/rule";

import { debounce } from "lodash-es";
import Api from "@/api/backend/api";
const { gridOptions } = useManhour();
const { gridServiceOptions } = useService();
const xGrid = ref();
const xServiceGrid = ref();
const gridEvent: VxeGridListeners<RowVO> = {
  proxyQuery() {
    console.log("数据代理查询事件");
    const grid = xGrid.value;
    // 获取表格中的数据
    // const data = grid.getTableData().fullData;
    // console.log(data);
  },
  proxyDelete() {
    console.log("数据代理删除事件");
  },
  proxySave() {
    console.log("数据代理保存事件");
  },
};
const gridServiceEvent: VxeGridListeners<RowVO> = {
  proxyQuery() {
    console.log("数据代理查询事件");
    // 获取表格中的数据
    // const data = grid.getTableData().fullData;
    // console.log(data);
  },
  proxyDelete() {
    console.log("数据代理删除事件");
  },
  proxySave() {
    console.log("数据代理保存事件");
  },
};
const ruleStore = useRuleStore();
const kindList = ref([]);
const kindData = ref([]);
const treeData = ref([]);
const open = ref(false);
const getData = async () => {
  kindData.value = await Api.kindController.tree();
};
const getList = async () => {
  kindList.value = await Api.kindController.list();
};
const kindTails = ref([]);
const columns = [
  {
    title: "id",
    dataIndex: "id",
    key: "name",
  },
  {
    dataIndex: "name",
    title: "名称",
    key: "name",
  },
  {
    dataIndex: "union_name",
    title: "分级名称",
    key: "union_name",
  },
  {
    dataIndex: "action",
    title: "操作",
    key: "action",
  },
];
const kindState = ref({
  id: null,
  pid: null,
  name: "",
});

const options = ref({
  service_data: [],
  kind_data: [],
  service_loading: false,
  kind_loading: false,
});
const formState = ref({
  service_id: null,
  kind_id: null,
});

const handleKindSearch = debounce(async (value) => {
  console.log("fetching kind", value);
  if (value == "") return;
  options.value.kind_data = [];
  options.value.kind_loading = true;
  let data = await Api.kindController.option({
    name: value,
  });
  options.value.kind_data = data.map((item) => {
    return {
      label: item.union_name,
      value: item.id,
    };
  });

  options.kind_loading = false;
}, 300);

const handleServiceSearch = debounce(async (value) => {
  console.log("fetching service", value);
  if (value == "") return;

  options.value.service_data = [];
  options.value.service_loading = true;
  let data = await Api.serviceController.option({
    name: value,
  });
  options.value.service_data = data.map((item) => {
    return {
      label: item.name,
      value: item.id,
    };
  });
  options.value.service_loading = false;
}, 300);
const handleServiceChange = (val) => {
  console.log(val);
};
const tableData = ref([]);
const onSubmit = async () => {
  tableData.value = await Api.manhourController.query(formState.value);
};
const formKindRef = ref();
const addKind = () => {
  open.value = true;
};
const editKind = (record) => {
  console.log(record);
  open.value = true;
  kindState.value = record;
};
const onSubmitKind = async () => {
  try {
    //先清空一下验证
    formKindRef.value.clearValidate();
    if (kindState.value.id != null) {
      await Api.kindController.update(
        { id: kindState.value.id },
        kindState.value
      );
    } else {
      await Api.kindController.store(kindState.value);
    }
    xGrid.value.commitProxy("query");
    formKindRef.value.resetFields();
    open.value = false;
  } catch (error) {
    formKindRef.value.validate();
  }
  await init();
};

//搜索
const kindSearchState = ref({
  name: "",
});
const onSearchKind = async () => {
  kindTails.value = await Api.kindController.option({
    name: kindSearchState.value.name,
  });
};
const init = async () => {
  await getData();
  await getList();
  kindTails.value = await Api.kindController.option({
    name: kindSearchState.value.name,
  });
  options.value.kind_data = kindTails.value;
};

const delKind = async (row) => {
  await Api.kindController.destroy({
    id: row.id,
  });
  await init();
};
const manhourOpen = ref(false);
const excelOpen = ref(false);
const previewExcel = () => {
  excelOpen.value = true;
};
const manhourForm = ref({
  id: null,
  service_id: null,
  kind_id: null,
  score: 0,
});
const addEventHour = () => {
  manhourForm.value = {
    id: null,
    service_id: null,
    kind_id: null,
    score: 0,
  };
  manhourOpen.value = true;
};
const editEventHour = async (row) => {
  let data = await Api.serviceController.option({
    name: "",
  });
  options.value.service_data = data.map((item) => {
    return {
      label: item.name,
      value: item.id,
    };
  });
  manhourForm.value = row;
  manhourOpen.value = true;
};
const delEventHour = async (row) => {
  await Api.manhourController.destroy({ id: row.id });
  xGrid.value.commitProxy("query");
};
// 工时
const formManhourRef = ref();
const onSubmitManhour = async () => {
  try {
    //先清空一下验证
    formManhourRef.value.clearValidate();
    if (manhourForm.value.id != null) {
      await Api.manhourController.update(
        { id: manhourForm.value.id },
        manhourForm.value
      );
    } else {
      await Api.manhourController.store(manhourForm.value);
    }
    xGrid.value.commitProxy("query");
    formManhourRef.value.resetFields();
  } catch (error) {
    formManhourRef.value.validate();
  }

  manhourOpen.value = false;
};
const addService = () => {
  serviceOpen.value = true;
};
// 服务项目
const serviceOpen = ref(false);
const serviceForm = ref({
  id: null,
  code: "",
  name: "",
});
const formServiceRef = ref();
const onSubmitService = async () => {
  try {
    //先清空一下验证
    formServiceRef.value.clearValidate();
    if (serviceForm.value.id != null) {
      await Api.serviceController.update(
        { id: serviceForm.value.id },
        serviceForm.value
      );
    } else {
      await Api.serviceController.store(serviceForm.value);
    }
    xServiceGrid.value.commitProxy("query");
    formServiceRef.value.resetFields();
    serviceOpen.value = false;
  } catch (error) {
    formServiceRef.value.validate();
  }
};
const editEventService = (row) => {
  serviceForm.value = row;
  serviceOpen.value = true;
};

const delEventService = async (row) => {
  await Api.serviceController.destroy({ id: row.id });
  xServiceGrid.value.commitProxy("query");
};
init();
</script>

<style scoped></style>
